﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace LianXian
{
    class BindingHelper
    {

        /*
         * 如果要检索由某个 ListBoxItem 的 DataTemplate 生成的 TextBlock 元素，
         * 您需要获得 ListBoxItem，在该 ListBoxItem 内查找 ContentPresenter，
         * 然后对在该 ContentPresenter 上设置的 DataTemplate 调用 FindName。 
         * */
        /// <summary>
        /// 查找由 DataTemplate 生成的元素。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="itemsControl"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T FindElementFromBindingData<T>(ItemsControl itemsControl, object data)
        {
            TreeViewItem myListBoxItem = (TreeViewItem)(itemsControl.ItemContainerGenerator.ContainerFromItem(data));
            ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
            DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
            T myTextBlock = (T)myDataTemplate.FindName(typeof (T).Name, myContentPresenter);
            return myTextBlock;
        }

        private static TChildItem FindVisualChild<TChildItem>(DependencyObject obj) where TChildItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is TChildItem)
                    return (TChildItem)child;
                else
                {
                    TChildItem childOfChild = FindVisualChild<TChildItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
    }
}
